const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const moment = require('../../lib/moment/moment.min.js');
import WxValidate from '../../lib/wx-validate/WxValidate.js'
//获取应用实例
const app = getApp();
var page;
var that;
Page({
  data: {
    unitId: '',
    isLoadUFR:false, //是否加载了房东的单元信息
    form: {
      unitName: '',
      houseName: '',
      photoUrl: '',
      content:{
        isShareholder:false
      },
    },
    isTouristRent:false,
    idMarks: [{ text: '合租人', val:true,  active: false }, { text: '承租人', val:false, active: true }],
    files: [],
    doorCardFile: [],
    ufroom: [],
    units: [],
    floors: [],
    rooms: [],
    unitIndex: 0,
    floorIndex: 0,
    roomsIndex: 0,
    multiArray: [],
    multiIndex: [0, 0, 0],
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    //检测是否是通过扫房东房源码入住
    if(util.isNullOrEmpty(app.globalData.ownersNo)){
      util.confirm.modal('请通过房东房源码扫码进入小程序认证入住！', '', ()=>{
        wx.navigateBack({
          delta:1
        })
      });
    }else{
      if (!app.globalData.isCert) {
        util.confirm.modal('您还未办理实名认证,请前去办理！', '温馨提示', function () {
          var p = encodeURIComponent(util.getCurrentPageUrlWithArgs());
          wx.navigateTo({
            url: '/pages/faceAuth/index?page='+p,
          })
        });
        return false;
      }
      if (options.unitName && options.floor && options.houseName){
        that.setData({
          'form.unitName': options.unitName,
          'form.floor': options.floor,
          'form.houseName': options.houseName,
        });
      }
      that.initValidate();
      page = util.page.clone();
      that.initUFR();
    }
  },
  onReady: function () { },
  onShow: function () {
    that.setData({
      isTouristRent: app.isTouristRent
    });
  },
  onPullDownRefresh() {
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
  },
  agree(e){
    let index = e.currentTarget.id;
    that.data.idMarks.forEach((i,n)=>{
      if(n == index){
        i.active = true;
      }else{
        i.active = false;
      }
    });
    that.setData({
      idMarks:that.data.idMarks
    });
  },
  submitForm: function (e) {
    if (util.isNullOrEmpty(app.globalData.ownersNo)){
      util.confirm.modal('请从房东提供的房源二维码扫码进入小程序！');
      return false;
    }
    var form = JSON.parse(JSON.stringify(that.data.form));
    var urls = []; //数据提交失败则删除已上传的文件,避免资源占用
    //图片地址整理
    util.confirm.openExt('您确定好了吗？', function () {
      var allFiles = that.data.files.concat();
      var upFs = allFiles.concat(that.data.doorCardFile);
      //that.setData({ isUpload:true});
      util.toast.loading('数据提交中...', 60);
      app.uploads(upFs).then(arr => {
        //console.log('arrrrrrrrrrrr', arr);
        if (arr.length > 0) {
          form.photoUrl = arr.map(function (f, n) {
            urls.push(f.filePath);
            return f.filePath;
          }).join(',');
        }
        if (form.photoUrl.indexOf(',') == 0) {
          form.photoUrl = form.photoUrl.substring(1);
        }
        //是否合租人
        var shareRent = that.data.idMarks.find((i,n)=>{
          return i.active;
        });
        form.content.isShareholder = shareRent.val;
        var p = {};
        p.news = form;
        p.isAllow = true;
        p.unitId = that.data.unitId;
        //that.setData({ isUpload: false });
        app.postPure(api.AuthCheckin, p).then(rsp => {
          util.confirm.modal('认证入住提交成功!请等待房东确认!可以查看通知页面！','温馨提示', ()=>{
            wx.switchTab({
              url: '/pages/index/index',
            })
          });
        }).catch((err) => {
          that.delFiles(urls);
          console.log(err);
        });
      });
    });
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      houseName: {
        required: true,
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      houseName: {
        required: '请选择房间号',
      }
    }
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  previewDoorCardImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.doorCardFile // 需要预览的图片http链接列表
    })
  },
  delFiles(urls){
    app.removeFiles(urls);
  },
  delDoorCardFile: function (e) { //删除门牌照
    let index = e.currentTarget.dataset.index;
    that.setData({
      doorCardFile: util.arrayUtil.delByIndex(that.data.doorCardFile, index),
    });
  },
  chooseDoorCardFileImage: function (e) {
    if (that.data.doorCardFile.length >= 1) {
      util.toast.fail('最多上传1张')
      return false;
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          doorCardFile: that.data.doorCardFile.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.files // 需要预览的图片http链接列表
    })
  },
  delRoomFile: function (e) {
    let index = e.currentTarget.dataset.index;
    that.setData({
      files: util.arrayUtil.delByIndex(that.data.files, index),
    });
  },
  chooseImage: function (e) {
    if (that.data.files.length > 3) {
      util.toast.fail('最多只能上传3张图片')
      return false;
    }
    wx.showActionSheet({
      itemList: ['上传照片', '追加上传'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            wx.chooseImage({
              count: 3,
              sizeType: ['original', 'compressed'],
              sourceType: ['album', 'camera'],
              success: function (res) {
                that.setData({
                  files: [].concat(res.tempFilePaths),
                });
              }
            });
          } else {
            wx.chooseImage({
              count: 6,
              sizeType: ['original', 'compressed'],
              sourceType: ['album', 'camera'],
              success: function (res) {
                if ((that.data.files.length + res.tempFilePaths.length) > 3) {
                  util.toast.fail('最多只能上传3张图片')
                } else {
                  that.setData({
                    files: that.data.files.concat(res.tempFilePaths),
                  });
                }
              }
            });
          }
        }
      }
    });
  },
  bindInput: function (e) {
    let name = e.currentTarget.dataset.name;
    let changeVal = {};
    changeVal[name] = e.detail.value;
    this.setData(changeVal);
  },
  initUFR() {
    if(that.data.isLoadUFR)return false;
    app.postForm(api.GetAllUnitInfo, { ownersNo: app.globalData.ownersNo, isAllow:true, retry:3}).then(res => {
      if (res.data) {
        that.setData({
          isLoadUFR: true,
          ufroom: res.data
        });
        var ufroom = that.data.ufroom;
        //楼号初始化
        ufroom.forEach(function (i, n) {
          that.data.units.push(i.unitName+'号楼');
          if (i.unitName === that.data.form.unitName){
            that.data.multiIndex[0] = n;
          }
        });
        var floors = ufroom[that.data.multiIndex[0]].floors;
        if (floors) {
          //楼层初始化
          floors.forEach(function (i, n) {
            that.data.floors.push((n + 1) + '层');
            if ((n + 1) === Number(that.data.form.floor)) {
              that.data.multiIndex[1] = n;
            }
          });

          floors[that.data.multiIndex[1]].forEach(function (i, n) {
            Object.keys(i).forEach(function (name) {
              that.data.rooms.push(name + '号');
              if (name === that.data.form.houseName) {
                that.data.multiIndex[2] = n;
              }
            });
          });
        }
        
        that.data.multiArray.push(that.data.units);
        that.data.multiArray.push(that.data.floors);
        that.data.multiArray.push(that.data.rooms);
        that.setData({
          multiIndex:that.data.multiIndex,
          multiArray: that.data.multiArray,
          'form.unitName': that.data.multiArray[0][that.data.multiIndex[0]].replace('号楼', ''),
          'form.houseName': that.data.multiArray[2][that.data.multiIndex[2]].replace('号', ''),
          unitId: ufroom[that.data.multiIndex[0]].id
        });
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  bindMultiPickerColumnChange: function (e) {
    //console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: that.data.multiArray,
      multiIndex: that.data.multiIndex
    };
    var ufroom = that.data.ufroom;
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        that.setData({
          floors: [],
          rooms: [],
          floorIndex: 0,
          roomsIndex: 0
        });
        //楼层初始化
        var floors = ufroom[data.multiIndex[0]].floors;
        if (floors) {
          floors.forEach(function (i, n) {
            that.data.floors.push((n + 1)+'层');
          });
          //房号初始化
          floors[that.data.floorIndex].forEach(function (i, n) {
            Object.keys(i).forEach(function (name) {
              that.data.rooms.push(name +'号');
            });
          });
          data.multiArray[1] = that.data.floors;
          data.multiArray[2] = that.data.rooms;
        }
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        break;
      case 1:
        that.setData({
          rooms: [],
          roomsIndex: 0
        });
        //房号初始化
        ufroom[data.multiIndex[0]].floors[data.multiIndex[1]].forEach(function (i, n) {
          Object.keys(i).forEach(function (name) {
            that.data.rooms.push(name+'号');
          });
        });
        data.multiArray[2] = that.data.rooms;
        data.multiIndex[2] = 0;
        break;
    }
    that.setData(data);
    that.setData({
      'form.unitName': data.multiArray[0][data.multiIndex[0]].replace('号楼',''),
      'form.houseName': data.multiArray[2][data.multiIndex[2]].replace('号', ''),
      unitId: ufroom[data.multiIndex[0]].id
    });
  },
})